package com.zhanghp.class01;

import static com.zhanghp.utils.CommonUtils.TEST_COUNT;
import static com.zhanghp.utils.CommonUtils.printDivingLine;

/**
 * 等概率返回0，1
 *
 * @author zhanghp
 * @date 2023-07-30 15:10
 */
public class Code04_MathRandomFunctionPropability {

    public static void main(String[] args) {
        printDivingLine();
        proveMathRandomEqualProbability();

        printDivingLine();
        processMathrandom();

        printDivingLine();
        xToxPower2();

        printDivingLine();
        xToOtherProbability();

        printDivingLine();

    }

    /**
     * 证明Math.random()等概率
     */
    public static void proveMathRandomEqualProbability() {
        double n = 0.85;
        long count = 0;
        for (int i = 0; i < TEST_COUNT; i++) {
            if (Math.random() < n) {
                count++;
            }
        }
        System.out.printf("%s%n", n + "出现的概率：" + (double) count / TEST_COUNT);
    }

    /**
     * 利用Math.random() [0,1) -> [0,10)
     * 并证明改造后等概率
     */
    public static void processMathrandom() {
        int[] arr = new int[10];
        for (int i = 0; i < TEST_COUNT; i++) {
            int rand = (int) (Math.random() * 10);
            arr[rand]++;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("%s%n", i + "出现的概率：" + ((double) arr[i]) / TEST_COUNT);
        }
    }

    /**
     * 任意的x，x属于[0,1)，[0,x)范围上的数出现概率由原来的x调整成x平方
     */
    public static void xToxPower2() {
        double num = 0.4;
        long count = 0;
        for (int i = 0; i < TEST_COUNT; i++) {
            if (Math.max(Math.random(), Math.random()) < num) {
                count++;
            }
        }
        System.out.printf("%s%n", num + ": x^2 = " + Math.pow(num, 2));
        System.out.printf("%s%n", num + "出现的概率：" + ((double) count) / TEST_COUNT);
    }

    /**
     * x属于[0,1)等概率，更改为 1 - (1-x)^2
     */
    public static void xToOtherProbability() {
        double num = 0.3;
        long count = 0;
        for (int i = 0; i < TEST_COUNT; i++) {
            if (Math.min(Math.random(), Math.random()) < num) {
                count++;
            }
        }
        System.out.printf("%s%n", num + ": 1 - (1 - x) ^ 2 = " + (1 - Math.pow(((double) 1 - num), 2)));
        System.out.printf("%s%n", num + "出现的概率：" + ((double) count) / TEST_COUNT);
    }



}
